<script lang="ts" setup>
import type { AppVersionForm } from '@/api/app/version/types'
import type { FormInstance } from 'element-plus'
import * as version from '@/api/app/version'
import { useUserStore } from '@/store/modules/user'
import type { AppTableView } from '@/api/app/types'

const dialogVisible = ref(false)
const defaultData = ():  AppVersionForm => ({
    version: '',
    upgradeMode: undefined,
    intro: '',
    file: undefined
})
const formData = ref(defaultData())
const fromRules = reactive({
    version: [
        { required: true, message: '请输入版本号', trigger: 'blur' }
    ],
    upgradeMode: [
        { required: true, message: '请选择升级方式', trigger: 'change' }
    ],
    intro: [
        { required: true, message: '请输入版本介绍', trigger: 'blur' }
    ],
    file: [
        { required: true, message: '请上传安装包', trigger: 'change' }
    ]
})
const formRef = ref<FormInstance>()

const upgradeModeOptions = ref<SelectOption[]>([])

onBeforeMount(async () => {
    upgradeModeOptions.value = await version.upgradeModeOptions()
})

const userStore = useUserStore()
const uploadRef = ref()
const uploadHeaders = ref({
    'Authorization': `Bearer ${userStore.getToken}`
})

const uploadSuccess = (response: any) => {
    console.log(response)
    if(response.success) {
        formData.value.file = response.data
    } else {
        ElMessage.error(response.message)
    }
}

const dialogProps = reactive<FormDialogProp>({
    title: '',
    id: undefined
})

const open = (props: FormDialogProp) => {
    formData.value = defaultData()
    
    dialogProps.title = props.title
    dialogProps.id = props.id
    dialogVisible.value = true

    nextTick(() => {
        if(uploadRef.value) {
            uploadRef.value.clearFiles()
        }
    })
}
defineExpose({
    open
})

const emit = defineEmits(['close'])

const submit = () => {
    if(!formRef.value) {
        return
    }

    formRef.value.validate(async (valid) => {
        if(valid) {
            const result = await version.release(dialogProps.id ?? '', formData.value)
            if(result.success) {
                ElMessage.success(result.message)
                dialogVisible.value = false
                emit('close')
            } else {
                ElMessage.error(result.message)
            }
        }
    })
}

const props = defineProps<{
    app: AppTableView
}>()
</script>

<template>
    <el-dialog v-model="dialogVisible" :title="dialogProps.title" width="50%">
        <el-form ref="formRef" :model="formData" :rules="fromRules" label-width="120px">
            <el-form-item label="版本号" prop="version">
                <el-input v-model="formData.version"></el-input>
            </el-form-item>
            <el-form-item label="升级方式" prop="upgradeMode">
                <el-select v-model="formData.upgradeMode">
                    <el-option v-for="option in upgradeModeOptions" :key="option.value" :label="option.text" :value="option.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="版本介绍" prop="intro">
                <el-input v-model="formData.intro" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }"></el-input>
            </el-form-item>
            <el-form-item label="安装包" prop="file">
                <el-upload ref="uploadRef" :action="`/api/app-release-file/${props.app.code}/upload`" name="file" :limit="1" :headers="uploadHeaders" :on-success="uploadSuccess">
                    <el-button size="small" type="primary">上传安装包</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传 .apk 格式的文件，且不超过 100MB</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="submit">保存</el-button>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>

</style>